// pages/index/productD/productD.js
const app = getApp();
import request from '../../../utils/http.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    shareble: false, //弹框
    visible: false,
    isRead: false,

    number: '', //电话
    name: '', //姓名
    times: '', //预约时间
    currentDate: '', //当前时间日期
    endDate: '',
    typeIndex: 0, //业务类型 1.陪诊 2.找专家医生 3.找特需专家 4.住院


    productName: '', //产品名称
    productInfo: '', //产品详情
    shuoMing: '',
    jiaGe: 0, //价格
    title: '', //标题
    xianShiJiaGe: 0, //显示价格
    tongYiJiaGe: 0, //统一零售价，打折后的实际销售单价
    yuFuKuanJiaGe: 0, //预付款价格
    peiZhenProductId: 0,
    jiaGeId: 0, //陪诊价格id
    isSubmitted: false, // 新增状态标志，默认为false，表示未提交
    isClick: false, //确认支付是否点击
    jiaGeList: [], //价格list

    currentIndex: 0,
    infoIsAll: false,


    code: '',
    phone: '',
    personId: 0,
    dianPuDengJi: 6,
    IsLogin: false,
    userInfo: {},
    hasUserInfo: false,

    
    guid_short:0,

    touXiangUrl: '',
    niCheng: '',
    tjr_id: 0,
    dianPuId: 0, //当前店铺ID
    login_dianPuId:0,//已登录店铺ID，用于判断需不需要重新登录
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    var date = new Date();
    var zero = '0'

    var nowYear = date.getFullYear();
    var nextYear = date.getFullYear() + 1;

    var nowMonth = date.getMonth() + 1;

    if (nowMonth < 10) {
      nowMonth = zero.concat(nowMonth)
    }

    var nowDay = date.getDate();

    if (nowDay < 10) {
      nowDay = zero.concat(nowDay)
    }

    wx.login({
      success: res => {
        that.setData({
          code: res.code
        })
      }
    })







    that.setData({
      login_dianPuId:(wx.getStorageSync(app.globalData.SHOPID) == '' || wx.getStorageSync(app.globalData.SHOPID) == undefined) ? 1 : wx.getStorageSync(app.globalData.SHOPID),
      personId: wx.getStorageSync(app.globalData.PERSON_ID),
      dianPuId: (options.dianPuId == '' || options.dianPuId == undefined) ? ((wx.getStorageSync(app.globalData.SHOPID) == '' || wx.getStorageSync(app.globalData.SHOPID) == undefined) ? 1 : wx.getStorageSync(app.globalData.SHOPID)) : options.dianPuId,
      tjr_id: (options.tjr_id == '' || options.tjr_id == undefined) ? wx.getStorageSync(app.globalData.TJR_ID) : options.tjr_id,
      touXiangUrl: wx.getStorageSync(app.globalData.TouXiang),
      niCheng: wx.getStorageSync(app.globalData.NiCheng),


      typeIndex: options.typeIndex,
      peiZhenProductId: options.peiZhenProductId,
      // dianPuId: options.dianPuId,
      currentDate: nowYear + '-' + nowMonth + '-' + nowDay,//日期选择器
      endDate: nextYear + '-' + nowMonth + '-' + nowDay,
      times: nowYear + '-' + nowMonth + '-' + nowDay,
    })

    if (options.scene) { //海报扫码
      let scene = decodeURIComponent(options.scene);
      console.log("scene:"+scene)
      that.setData({
        dianPuId: scene.split("_")[0],
        tjr_id: scene.split("_")[1],
        peiZhenProductId: scene.split("_")[2],
        guid_short:scene.split("_")[3]==''||scene.split("_")[3]==null?0:scene.split("_")[3],
      })
    }
    wx.setStorageSync(app.globalData.SHOPID, that.data.dianPuId)
    wx.setStorageSync(app.globalData.TJR_ID, that.data.tjr_id)
    if(that.data.login_dianPuId==that.data.dianPuId && that.data.dianPuId>0){
      that.setData({
        IsLogin:wx.getStorageSync(app.globalData.LOGINSTATUS)==true?true:false,
      })

    }else{
      that.setData({
        IsLogin:false,
      })
    }
    wx.setStorageSync(app.globalData.LOGINSTATUS, that.data.IsLogin)
  },


  isAllInfo() {
    if (this.data.number.length == 11 && this.data.name != '' && this.data.times != '' && this.data.isRead) {
      this.setData({
        infoIsAll: true
      })
    } else {
      this.setData({
        infoIsAll: false
      })
    }
  },


  onVisibleChange(e) {
    this.setData({
      visible: !this.data.visible,
    });
  },

  //点击check
  changeCheck() {
    this.setData({
      isRead: !this.data.isRead,
    });
    this.isAllInfo()
  },


  //提交预约信息
  YuYueTijiao: function () {
    var that = this
    if (that.data.isSubmitted) {
      wx.showToast({
        title: '请勿重复提交',
        icon: "none",
        duration: 1000,
        mask: false,
      });
      return;
    }

    wx.showModal({
      title: '预约确认',
      content: '请确认您的预约信息!!!',
      showCancel: true,
      cancelText: '取消',
      confirmText: '确定',
      success(confirmRes) {
        if (confirmRes.confirm) {
          that.setData({
            isSubmitted: true
          });
          let data = {
            openId: wx.getStorageSync(app.globalData.OPENID),
            dianPuId: that.data.dianPuId,
            peiZhenProductId: that.data.peiZhenProductId,
            peiZhenJiaGeId: that.data.jiaGeId,
            lianXiRenXingMing: that.data.name,
            lianXiRenPhone: that.data.number,
            qiWangFuWuShiJian: that.data.times
          };
          request.get('peiZhenOrderForm/addOrderForm', data, res => {
            console.log("预约信息:" + JSON.stringify(res.data));
            wx.hideLoading()
            if (res.data.status == 1) {
              if (res.data.bInvokeWechatPay == 1) {
                wx.requestPayment({
                  timeStamp: res.data.map.timeStamp,
                  nonceStr: res.data.map.nonce_str,
                  package: 'prepay_id=' + res.data.map.prepay_id,
                  signType: 'MD5',
                  paySign: res.data.map.paySign,
                  success: function (ress) {
                    wx.showToast({
                      title: "支付成功！", // 提示的内容
                      icon: "none", // 图标，默认success
                      duration: 1000, // 提示的延迟时间，默认1500
                      mask: false, // 是否显示透明蒙层，防止触摸穿透
                      complete: function () {
                        setTimeout(function () {
                          wx.redirectTo({
                            url: '/pkg_pz/pages/TwoYuyue/TwoYuyue',
                          })
                        }, 1000)
                      }
                    })
                  },
                  fail: function (ress) {
                    wx.showToast({
                      title: "支付失败！", // 提示的内容
                      icon: "none", // 图标，默认success
                      duration: 1500, // 提示的延迟时间，默认1500
                      mask: false, // 是否显示透明蒙层，防止触摸穿透
                      complete: function () {
                        setTimeout(function () {
                          wx.redirectTo({
                            url: '/pkg_pz/pages/Pzyuyue/Pzyuyue',
                          })
                        }, 1000)
                      }
                    })
                    that.setData({
                      isClick: false
                    })
                  },
                  complete: function (ress) {}
                });
              } else {
                that.colseShare()
                wx.showToast({
                  title: '预约成功',
                  icon: 'success',
                  duration: 1500,
                  mask: false,
                  complete: function () {
                    setTimeout(function () {
                      wx.redirectTo({
                        url: '/pkg_pz/pages/Pzyuyue/Pzyuyue',
                      })
                    }, 1500)
                  }
                });
              }
            } else { //订单生成失败
              wx.showToast({
                title: "订单生成失败！", // 提示的内容
                icon: "none", // 图标，默认success
                duration: 3000, // 提示的延迟时间，默认1500
                mask: false, // 是否显示透明蒙层，防止触摸穿透
                complete: function () {
                  that.setData({
                    isClick: false
                  })
                }
              })
            }
          });
        } else if (confirmRes.cancel) {
          console.log('用户点击了取消');
        }
      },
    });
  },

  //选项按钮
  handleSelect(e) {
    var jiaGeId = e.currentTarget.dataset.id;
    var yuFuKuanJiaGe = e.currentTarget.dataset.yf;
    var index = e.currentTarget.dataset.index;
    this.setData({
      currentIndex: index,
      jiaGeId: jiaGeId,
      yuFuKuanJiaGe: yuFuKuanJiaGe,
    });

    this.isAllInfo()
  },


  //虚拟支付
  zhifu: function (dingDanHao) {
    var that = this
    let data = {
      dingDanHao: dingDanHao,
    }
    request.get('OrderForm20231109/xiuNiZhiFu', data, res => {
      wx.hideLoading();
      wx.showToast({
        title: '支付成功', // 提示的内容
        icon: "none", // 图标，默认success
        duration: 1500, // 提示的延迟时间，默认1500
        mask: false, // 是否显示透明蒙层，防止触摸穿透
      })
    })
  },


  //获取陪诊产品详情
  getOnePeiZhenProduct: function () {
    var that = this
    let data = {
      peiZhenProductId: that.data.peiZhenProductId
    }
    request.get('peiZhenProduct/getOnePeiZhenProduct', data, res => {
      console.log("获取陪诊产品详情:" + JSON.stringify(res.data))
      that.setData({
        productName: res.data.productName,
        productInfo: res.data.productInfo,
        jiaGe: res.data.jiaGe,
        jiaGeList: res.data.jiaGeList,
        shuoMing: res.data.shuoMing,
        jiaGeListlength: res.data.jiaGeList.length,
        yuFuKuanJiaGe: res.data.jiaGeList[0].yuFuKuanJiaGe
      })
      if (res.data.jiaGeList.length > 0) {
        that.setData({
          jiaGeId: res.data.jiaGeList[0].jiaGeId,
        })
      }
    }, err => {
      wx.showToast({
        title: '获取信息失败', // 提示的内容
        icon: "none", // 图标，默认success
        duration: 1000, // 提示的延迟时间，默认1500
        mask: false, // 是否显示透明蒙层，防止触摸穿透
      })
    })

  },


  //点击显示弹框
  pickShare() {
    this.setData({
      shareble: true,
    })
  },

  //popo弹框或关闭
  toserveInfo(e) {

    this.setData({
      visible: !this.data.visible,
    });
  },

  // 关闭弹框
  colseShare: function () {
    this.setData({
      shareble: false,
    })
  },



  //姓名
  onNameInput: function (event) {
    this.setData({
      name: event.detail.value,
    });

    this.isAllInfo()
  },

  //手机号
  onnumInput: function (event) {
    this.setData({
      number: event.detail.value,
    });
    this.isAllInfo()
  },


  bindDateChange(e) {
    this.setData({
      times: e.detail.value
    })
    this.isAllInfo()
  },



  //拨打电话
  makePhoneCallAction() {
    wx.makePhoneCall({
      phoneNumber: '4009930399',
      success: function (res) {},
      fail: function (res) {}, //接口调用失败的回调函数
      complete: function (res) {}, //接口调用结束的回调函数（调用成功、失败都会执行）
    })
  },

   //V3.0 获取手机号码
   getPhoneNumber: function (e) {
    var that = this
    if (e.detail.errMsg == "getPhoneNumber:ok") { //允许
      that.decryptPhone(e);
    } else { //拒绝
      wx.showToast({
        title: "请授权！！", // 提示的内容
        icon: "none", // 图标，默认success
        duration: 3000, // 提示的延迟时间，默认1500
        mask: false, // 是否显示透明蒙层，防止触摸穿透
      })
    }
  },


   //V3.0 解密手机号码
  decryptPhone: function (e) {

    wx.showLoading({
      title: '解析中...',
      mask: true
    })

    var that = this;
    let code=that.data.code;
    let iv = e.detail.iv;
    let encryptedData = e.detail.encryptedData;

    wx.request({
      url: app.globalData.base_url + 'resource/getWXPhoneDirect',
      data: {
        iv: iv,
        js_code:code,
        encrypted: encryptedData,
        tuiJianRenId:that.data.tjr_id,
        dianPuId:that.data.dianPuId
      },
      success: function (res) {
       console.log("解密手机号码:" + JSON.stringify(res.data))
       
        if(res.data.purePhoneNumber=='' || res.data.status==500){

          wx.showToast({
            title: '解析异常，右上角重新进入小程序', // 提示的内容
            icon: "none", // 图标，默认success
            duration: 3000, // 提示的延迟时间，默认1500
            mask: false, // 是否显示透明蒙层，防止触摸穿透
          })

        }else{
          wx.setStorageSync(app.globalData.OPENID, res.data.openId)
          wx.setStorageSync(app.globalData.PERSON_ID, res.data.personId)
          wx.setStorageSync(app.globalData.TOKEN, res.data.token)
          wx.setStorageSync(app.globalData.PHONENUMBER, res.data.purePhoneNumber)
          wx.setStorageSync(app.globalData.LOGINSTATUS, true)
          wx.setStorageSync(app.globalData.NiCheng, res.data.niCheng)
          wx.setStorageSync(app.globalData.TouXiang, res.data.touXiangUrl)

          that.setData({    
            personId: res.data.personId,
            IsLogin:true,
            touXiangUrl: res.data.touXiangUrl,
            niCheng: res.data.niCheng,  
          })
        }
      },
      fail: function (err) {
        that.setData({
          IsLogin:false
        })
        wx.showToast({
          title: '获取数据失败,请检查网络', // 提示的内容
          icon: "none", // 图标，默认success
          duration: 3000, // 提示的延迟时间，默认1500
          mask: false, // 是否显示透明蒙层，防止触摸穿透
        })
      },
      complete: function (res) {
        wx.hideLoading();
      }
    })
  },




  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getOnePeiZhenProduct();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: app.globalData.Sharetitle,
      imageUrl: app.globalData.ShareimageUrl,
      path: '/pages/index/index?tjrId=' + wx.getStorageSync(app.globalData.PersonId)
    }
  }
})